package com.yunquan.ohana.ui.calendar.task.add

import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.text.InputType
import androidx.activity.result.ActivityResult
import androidx.core.content.ContextCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.google.gson.Gson
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.BaseActivity
import com.yunquan.ohana.databinding.ActivityTaskAddBinding
import com.yunquan.ohana.entity.TaskEntity
import com.yunquan.ohana.utils.StringUtils
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.Locale

class TaskAddActivity : BaseActivity<ActivityTaskAddBinding, TaskAddViewModel>() {
    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_task_add
    }

    override fun initVariableId(): Int {
        return BR.taskAddViewModel
    }

    override fun initParam() {
        super.initParam()
        Locale.setDefault(Locale("en"))
        // 设置背景颜色
        window.statusBarColor = ContextCompat.getColor(this, R.color.c_F6)
        // 设置文字颜色（true = 黑色文字，false = 白色文字）
        val controller = WindowInsetsControllerCompat(window, window.decorView)
        controller.isAppearanceLightStatusBars = true
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        val bundle = intent.extras
        bundle?.let {
            viewModel!!.mDeviceId = it.getString("deviceId")
            viewModel!!.mRoleId = it.getString("roleId")
            viewModel!!.isUserType.set(it.getBoolean("userType", false))
            val dataJson = it.getString("data")
            if (!StringUtils.isEmpty(dataJson)) {
                binding!!.tvOperator.setText(R.string.save)
                viewModel!!.title.set(getString(R.string.edit_task))
                viewModel!!.mTaskEntity = Gson().fromJson(dataJson, TaskEntity::class.java)
                val isUseRoleIdIndex = viewModel!!.mTaskEntity?.tasksToRoleVos?.indexOfFirst { taskRole ->
                    taskRole.roleId == viewModel!!.mRoleId
                } ?: -1
                viewModel!!.isShowDelete.set(isUseRoleIdIndex >= 0)
                viewModel!!.taskTitle.set(viewModel!!.mTaskEntity?.title)
                viewModel!!.taskEmoji.set(viewModel!!.mTaskEntity?.emoji)
                viewModel!!.mTaskEntity?.startDate?.let { timestamp ->
                    val dateTime = LocalDateTime.ofInstant(
                        Instant.ofEpochSecond(timestamp.toLong()),
                        ZoneId.systemDefault()
                    )
                    binding!!.cbDate.isChecked = true
                    viewModel!!.mTaskDate = dateTime.toLocalDate()
                    viewModel!!.taskDate.set(dateTime.format(viewModel!!.mDateFormat))
                }
                viewModel!!.mTaskEntity?.reminderTime?.let { timestamp ->
                    val dateTime = LocalDateTime.ofInstant(
                        Instant.ofEpochSecond(timestamp.toLong()),
                        ZoneId.systemDefault()
                    )
                    binding!!.cbTime.isChecked = true
                    viewModel!!.mTaskTime = dateTime.toLocalTime()
                    viewModel!!.taskTime.set(dateTime.format(viewModel!!.mTimeFormat))
                }
                viewModel!!.mTaskEntity?.endDate?.let { timestamp ->
                    val dateTime = LocalDateTime.ofInstant(
                        Instant.ofEpochSecond(timestamp.toLong()),
                        ZoneId.systemDefault(),
                    )
                    viewModel!!.mRepeatsUntilDate = dateTime.toLocalDate()
                    viewModel!!.repeatsUntil.set(dateTime.format(viewModel!!.mDateFormat))
                }
                when (viewModel!!.mTaskEntity?.isRepeat) {
                    "1" -> {
                        viewModel!!.isRepeats.set(true)
                        viewModel!!.everyTypeIndex.set(1)
                    }

                    "2" -> {
                        viewModel!!.isRepeats.set(true)
                        viewModel!!.everyTypeIndex.set(2)
                        binding!!.rbDay.isChecked = true
                    }

                    "3" -> {
                        viewModel!!.isRepeats.set(true)
                        viewModel!!.everyTypeIndex.set(3)
                        binding!!.rbWeek.isChecked = true
                    }

                    "4" -> {
                        viewModel!!.isRepeats.set(true)
                        viewModel!!.everyTypeIndex.set(4)
                        binding!!.rbMonth.isChecked = true
                    }

                    "5" -> {
                        viewModel!!.isRepeats.set(true)
                        viewModel!!.everyTypeIndex.set(5)
                        binding!!.rbYear.isChecked = true
                    }

                    else -> {
                        viewModel!!.isRepeats.set(false)
                        viewModel!!.everyTypeIndex.set(0)
                    }
                }
            } else {
                binding!!.tvOperator.setText(R.string.edit)
                viewModel!!.title.set(getString(R.string.add_task))
                viewModel!!.isShowDelete.set(false)
            }
        }
        viewModel!!.getProfilesList()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        binding!!.etEmoji.inputType = InputType.TYPE_CLASS_TEXT
        binding!!.etEmoji.isCursorVisible = true
        binding!!.etEmoji.filters = arrayOf(InputFilter { source, _, _, _, _, _ ->
            if (source == null) return@InputFilter null
            // 保留表情字符
            val filtered = source.filter { Character.getType(it) == Character.SURROGATE.toInt() }
            filtered.ifEmpty { "" }
        })
        viewModel!!.ui.observe(this) {
            if (it == 0) {
                setResult(1004)
                finish()
            }
        }
    }

    override fun onActivityResult(result: ActivityResult) {
        super.onActivityResult(result)
        if (result.resultCode == 1001) {
            viewModel!!.getProfilesList()
        }
    }
}